import axios from 'axios'
import Vue from 'vue'
import { Loading } from 'element-ui'
import store from '@/store'
import qs from 'qs'

axios.defaults.baseURL = '/api'
axios.defaults.withCredentials = true
axios.defaults.crossDomain = true
axios.interceptors.request.use(config => {
  config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
  if (config.method === 'post') {
    config.data = qs.stringify({
      ...config.data
    })
  }
  return config;
})
axios.interceptors.response.use(response => {
  return response.data
}, (err) => {
  Vue.prototype.$message.error("快滚！快滚！快滚！内部错误，你无法解决！")
  return new Promise(() => { })
})

// mixinLoading(axios.interceptors)

let loading
let loadingCount = 0
function mixinLoading (interceptors) {
  interceptors.request.use(loadingRequestInterceptor)
  interceptors.response.use(
    loadingResponseInterceptor,
    loadingResponseErrorInterceptor
  )

  function loadingRequestInterceptor (config) {
    if (!loading) {
      loading = Loading.service({
        target: 'body',
        background: 'transparent',
        text: '载入中',
      })
      store.commit('global/setAxiosLoading', true)
    }
    loadingCount++

    return config
  }

  function handleResponseLoading () {
    loadingCount--
    if (loadingCount === 0) {
      loading.close()
      loading = null
      store.commit('global/setAxiosLoading', false)
    }
  }

  function loadingResponseInterceptor (response) {
    handleResponseLoading()
    return response
  }

  function loadingResponseErrorInterceptor (e) {
    handleResponseLoading()
    throw e
  }
}

export default axios
